import os
import sys
import pandas as pd
import datetime
from MainConsolidator import MainConsolidator

class handler(object):
    @staticmethod
    def module_name():
        return 'Муфта ТЭСЦ-5'
    @staticmethod
    def handle(row:pd.Series,consolidator:MainConsolidator)->pd.Series:
        product_up=None
        try:
            product = row["Первичный продукт"]
            carving_type = consolidator.carving_type(row["Тип резьбы <Производство>"])
            diametr_led = consolidator.nearest_in_guid("Параметры по Продукту ТЭСЦ-5",
                f"`Производство`=='Муфта ТЭСЦ-5' and `Продукт`=='{product}'",
                "Доп параметр1",
                row["Диаметр, мм <Производство>"],
                "Доп параметр2")
            diametr_led_s = str(diametr_led).replace(".0","")
            strength_group = consolidator.scalar_in_guid("Группа по классу прочности для муфт", 
                f"`Марка стали`=='{row['Класс прочности <Производство>']}'",
                "Группа прочности")
            if pd.isna(strength_group): strength_group="ПD"
            print(f"{product} ; carving_type: {carving_type}; diametr_led_s: {diametr_led_s}; strength_group: {strength_group}")
            # Наименование_УП = Продукт & Диам_тип & " " & Гр_прочн & " " & Резьба_тип
            product_up=f"{product}{diametr_led_s} {strength_group} {carving_type}"
            row["error"] = pd.NA
        except Exception as exp: 
            row["error"] = f"{exp}"
        finally:
            row["Продукт УП"]=product_up
            row["Время укрупнения"]=datetime.datetime.now()
            return row
        
    def debug_handle(self,inputDf:pd.DataFrame,consolidator:MainConsolidator,module:str=None)->pd.DataFrame:
        try:
            if module is None: return inputDf.apply(lambda row: self.handle(row,consolidator), axis=1)
            else: return inputDf[inputDf["Производство2"]==module].apply(lambda row: self.handle(row,consolidator), axis=1)
        except: raise
    
    def get_compiled(self):
        code:str=f"print('{__file__}')"
        try:
            with open(__file__,encoding="utf-8",mode="r") as f:
                code=f.read()
        except Exception as exp: 
            code=f"print('error: {exp}')"
        finally:
            cc = compile(code,"","exec")
            return cc

if __name__=="__sleeve_t5__":
    consolidator:MainConsolidator
    record:pd.Series
    result:pd.Series
    result = handler.handle(record,consolidator)

